<template>
  <view class="container">
    <!-- 顶部用户信息 -->
    <view class="user-header">
      <image src="/static/images/user-bg.jpg" mode="widthFix" class="header-bg"></image>
      <view class="user-info">
        <image :src="userInfo.avatar" mode="widthFix" class="user-avatar" @click="handleAvatarClick"></image>
        <view class="user-name" @click="handleAvatarClick">{{ userInfo.isLogin ? userInfo.name : '点击登录' }}</view>
        <view class="user-level" v-if="userInfo.isLogin">
          <uni-icons type="medal" size="14" color="#FFCC00"></uni-icons>
          <text>{{ userInfo.level || '职场新人 Lv.1' }}</text>
        </view>
      </view>
    </view>
    
    <!-- 功能菜单 -->
    <view class="menu-list">
      <view class="menu-group">
        <view class="menu-item" @click="toMyReviews">
          <uni-icons type="edit" size="20" color="#36D" class="menu-icon"></uni-icons>
          <text class="menu-text">我的评价</text>
          <uni-icons type="arrowright" size="18" color="#ccc" class="menu-arrow"></uni-icons>
        </view>
        <view class="menu-item" @click="toMyCollections">
          <uni-icons type="star" size="20" color="#F93" class="menu-icon"></uni-icons>
          <text class="menu-text">我的收藏</text>
          <uni-icons type="arrowright" size="18" color="#ccc" class="menu-arrow"></uni-icons>
        </view>
        <view class="menu-item" @click="toBrowseHistory">
          <uni-icons type="eye" size="20" color="#6C6" class="menu-icon"></uni-icons>
          <text class="menu-text">浏览历史</text>
          <uni-icons type="arrowright" size="18" color="#ccc" class="menu-arrow"></uni-icons>
        </view>
      </view>
      
      <view class="menu-group">
        <view class="menu-item" @click="toSettings">
          <uni-icons type="setting" size="20" color="#666" class="menu-icon"></uni-icons>
          <text class="menu-text">设置</text>
          <uni-icons type="arrowright" size="18" color="#ccc" class="menu-arrow"></uni-icons>
        </view>
        <view class="menu-item" @click="toFeedback">
          <uni-icons type="chat" size="20" color="#666" class="menu-icon"></uni-icons>
          <text class="menu-text">意见反馈</text>
          <uni-icons type="arrowright" size="18" color="#ccc" class="menu-arrow"></uni-icons>
        </view>
        <view class="menu-item" @click="toAbout">
          <uni-icons type="info" size="20" color="#666" class="menu-icon"></uni-icons>
          <text class="menu-text">关于我们</text>
          <uni-icons type="arrowright" size="18" color="#ccc" class="menu-arrow"></uni-icons>
        </view>
      </view>
    </view>
    
    <!-- 退出登录按钮 -->
    <button class="logout-btn" @click="logout" v-if="userInfo.isLogin">退出登录</button>
  </view>
</template>

<script>
import { getUserInfo, logout, isLogin } from '@/api/user'
import config from '@/common/config'

export default {
  data() {
    return {
      userInfo: {
        isLogin: false,
		userId:0,
        name: '游客',
        avatar: '/static/images/default-avatar.png',
        username: '',
        level: '职场新人 Lv.1',
        nickname: '',
        phonenumber: '',
        email: ''
      }
    };
  },
  onShow() {
    // 每次显示页面时检查登录状态
    this.checkLoginStatus();
  },
  methods: {
    // 检查登录状态 - 符合RuoYi框架规范
    async checkLoginStatus() {
      try {
        // 从本地存储获取token和用户信息
        const token = uni.getStorageSync('Token');
        
        if (token) {
          try {
            // 先检查本地缓存的用户信息
            const cachedUserInfo = uni.getStorageSync('UserInfo');
            if (cachedUserInfo) {
              // 转换缓存的用户信息以适配界面显示
              let avatar = cachedUserInfo.avatarUrl || cachedUserInfo.avatar || '/static/images/user-avatar.png';
              // 拼接完整的头像URL（如果是相对路径且不是静态资源）
              if (avatar.startsWith('/') && !avatar.startsWith('/static/')) {
                avatar = config.baseUrl + avatar;
              }
              this.userInfo = {
                isLogin: true,
				userId: cachedUserInfo.userId || 0,
                name: cachedUserInfo.nickname || cachedUserInfo.nickName || cachedUserInfo.username || cachedUserInfo.userName || cachedUserInfo.name || '用户',
                avatar: avatar,
                level: cachedUserInfo.level || cachedUserInfo.userLevel || '职场达人 Lv.1',
                username: cachedUserInfo.username || cachedUserInfo.userName || '',
                nickname: cachedUserInfo.nickname || cachedUserInfo.nickName || '',
                phonenumber: cachedUserInfo.phonenumber || cachedUserInfo.phoneNumber || '',
                email: cachedUserInfo.email || ''
              };
            }
            
            // 然后从服务器获取最新用户信息
            const res = await getUserInfo();
            if (res.code === 200 && res.data) {
              // RuoYi框架返回的数据结构兼容
              const userData = res.data.user || res.data;
              const updatedUserInfo = {
				userId:userData.userId||0,
                username: userData.username || userData.userName || '',
                nickname: userData.nickname || userData.nickName || '',
                level: userData.level || userData.userLevel || '职场达人 Lv.1',
                phonenumber: userData.phonenumber || userData.phoneNumber || '',
                email: userData.email || '',
                avatar: userData.avatarUrl || userData.avatar || '/static/images/user-avatar.png'
              };
              
              // 更新缓存的用户信息
              uni.setStorageSync('UserInfo', updatedUserInfo);
              
              // 拼接完整的头像URL（如果是相对路径且不是静态资源）
              let avatar = updatedUserInfo.avatar;
              if (avatar.startsWith('/') && !avatar.startsWith('/static/')) {
                avatar = config.baseUrl + avatar;
              }
              
              // 更新显示的用户信息
              this.userInfo = {
                isLogin: true,
				userId:updatedUserInfo.userId||0,
                name: updatedUserInfo.nickname || updatedUserInfo.username || '用户',
                avatar: avatar,
                level: updatedUserInfo.level,
                username: updatedUserInfo.username,
                nickname: updatedUserInfo.nickname,
                phonenumber: updatedUserInfo.phonenumber,
                email: updatedUserInfo.email
              };
            } else {
              // 获取用户信息失败，清除token
              this.clearLoginInfo();
            }
          } catch (error) {
            console.error('获取用户信息失败:', error);
            // 错误码401或未授权，清除登录信息
            if (error.code === 401 || error.response?.status === 401) {
              this.clearLoginInfo();
            }
          }
        } else {
          // 没有token，未登录状态
          this.clearLoginInfo();
        }
      } catch (error) {
        console.error('检查登录状态失败:', error);
        // 出错时重置用户信息
        this.clearLoginInfo();
      }
    },
    
    // 清除登录信息
    clearLoginInfo() {
      uni.removeStorageSync('Token');
      uni.removeStorageSync('UserInfo');
      this.userInfo = {
        isLogin: false,
        name: '游客',
        avatar: '/static/images/user-avatar.png',
        username: '',
        level: '职场新人 Lv.1',
        nickname: '',
        phonenumber: '',
        email: ''
      };
    },
    
    // 处理头像点击事件
    handleAvatarClick() {
      if (!this.userInfo.isLogin) {
        this.toLogin();
      } else {
        // 已登录用户点击头像可以跳转到个人资料编辑页面
        // 或者弹出选择更换头像的菜单
        this.navigateIfAuthenticated('/pages/mine/profile-edit');
      }
    },
    
    // 跳转到登录页面
    toLogin() {
      uni.navigateTo({
        url: '/pages/mine/login'
      });
    },
    
    // 退出登录 - 符合RuoYi框架规范
    async logout() {
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: async res => {
          if (res.confirm) {
            try {
              // 调用退出登录接口
              await logout({ withToken: true });
            } catch (error) {
              console.error('退出登录失败:', error);
              // 即使接口失败，也要清除本地登录信息
            } finally {
              // 清除本地存储的token和用户信息
              this.clearLoginInfo();
              
              uni.showToast({
                title: '已退出登录',
                icon: 'none'
              });
            }
          }
        }
      });
    },
    
    // 带认证检查的页面跳转
    navigateIfAuthenticated(pagePath) {
      if (!this.userInfo.isLogin) {
        this.toLogin();
        return;
      }
      this.navigatePage(pagePath);
    },
    
    // 通用页面跳转方法
    navigatePage(pagePath) {
      try {
        uni.navigateTo({
          url: pagePath,
          fail: () => {
            // 尝试重定向
            try {
              uni.redirectTo({
                url: pagePath,
                fail: () => {
                  uni.showToast({
                    title: '该功能暂未开放',
                    icon: 'none'
                  });
                }
              });
            } catch (redirectError) {
              uni.showToast({
                title: '该功能暂未开放',
                icon: 'none'
              });
            }
          }
        });
      } catch (error) {
        console.error('跳转失败:', error);
        uni.showToast({
          title: '该功能暂未开放',
          icon: 'none'
        });
      }
    },
    
    // 跳转到我的评价页面
    toMyReviews() {
      this.navigateIfAuthenticated('/pages/mine/my-reviews');
    },
    
    // 跳转到我的收藏页面
    toMyCollections() {
      this.navigateIfAuthenticated('/pages/mine/my-collections');
    },
    
    // 跳转到浏览历史页面
    toBrowseHistory() {
      this.navigateIfAuthenticated('/pages/mine/browse-history');
    },
    
    // 跳转到设置页面
    toSettings() {
      this.navigateIfAuthenticated('/pages/mine/settings');
    },
    
    // 跳转到反馈页面
    toFeedback() {
      this.navigateIfAuthenticated('/pages/mine/feedback');
    },
    
    // 跳转到关于页面
    toAbout() {
      // 关于我们页面不需要登录
      this.navigatePage('/pages/mine/about');
    }
  }
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.user-header {
  position: relative;
  width: 100%;
}

.header-bg {
  width: 100%;
  height: 160px;
  object-fit: cover;
}

.user-info {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.user-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 3px solid #fff;
  margin-bottom: 10px;
}

.user-name {
  font-size: 18px;
  color: #fff;
  font-weight: bold;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.user-level {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #fff;
  margin-top: 5px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.menu-list {
  flex: 1;
  padding: 15px;
}

.menu-group {
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 15px;
  overflow: hidden;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-icon {
  margin-right: 15px;
}

.menu-text {
  flex: 1;
  font-size: 16px;
  color: #333;
}

.logout-btn {
  width: 90%;
  height: 45px;
  line-height: 45px;
  background-color: #fff;
  color: #F33;
  border: 1px solid #F33;
  border-radius: 8px;
  font-size: 16px;
  margin: 20px auto;
}
</style>
